package kau.controller;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import kau.dao.AttendInfoDAOImpl;
import kau.dao.BoardDAOImpl;
import kau.dao.CourseDAOImpl;
import kau.dao.CurriPlanDAOImpl;
import kau.dao.CurriculumDAOImpl;
import kau.dao.CustomerDAOImpl;
import kau.dao.RegisterationDAOImpl;
import kau.dao.TagDAOImpl;
import kau.vo.AttendInfo;
import kau.vo.Board;
import kau.vo.Course;
import kau.vo.CurriPlan;
import kau.vo.Curriculum;
import kau.vo.Registeration;
import kau.vo.Tag;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import org.springframework.web.servlet.view.RedirectView;

import common.DateUtil;

public class CourseAction extends MultiActionController {

	public ModelAndView getAllCourses(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView nextPage = new ModelAndView();
		ArrayList<Course> courseList = CourseDAOImpl.getInstance()
				.getAllCourses();
		request.setAttribute("courseList", courseList);
		nextPage.setViewName("index.jsp?contentMenu=/admin/menuPage.jsp&content=/admin/tagRegisteration.jsp");
		return nextPage;
	}

	public ModelAndView getAllTags(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView nextPage = new ModelAndView();
		ArrayList<Tag> tagList = TagDAOImpl.getInstance().getAllTagLists();
		request.setAttribute("tagList", tagList);
		nextPage.setViewName("index.jsp?contentMenu=/admin/menuPage.jsp&content=/admin/tagList.jsp");
		return nextPage;
	}

	public ModelAndView tagRegisteration(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView nextPage = new ModelAndView();
		System.out.println("tagRegisteration");
		int courseId = Integer.parseInt(request.getParameter("courseId"));
		String tagId = request.getParameter("tagId");
		Tag tag = new Tag(courseId, tagId);
		TagDAOImpl.getInstance().insert(tag);
		nextPage.setViewName("getAllTags.course");
		return nextPage;
	}

	public ModelAndView tagDelete(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView nextPage = new ModelAndView();
		System.out.println("tagDelete");

		String tagId = request.getParameter("tagId");
		TagDAOImpl.getInstance().delete(tagId);
		nextPage.setViewName("getAllTags.course");

		return nextPage;
	}

	public ModelAndView courseMain(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView nextPage = new ModelAndView();
		// System.out.println("courseMain");

		int courseId;
		int bNumber1, bNumber2, bNumber3;
		String courseName;
		String lecturer;
		int memberCount;
		String sinceDate;

		courseId = Integer.parseInt(request.getParameter("courseId"));
		courseName = CourseDAOImpl.getInstance().getCourse(courseId)
				.getCourseName();
		bNumber1 = BoardDAOImpl.getInstance().getBoard(courseId, "공지사항")
				.getbNumber();
		bNumber2 = BoardDAOImpl.getInstance().getBoard(courseId, "자유게시판")
				.getbNumber();
		bNumber3 = BoardDAOImpl.getInstance().getBoard(courseId, "질문게시판")
				.getbNumber();
		lecturer = CourseDAOImpl.getInstance().getCourse(courseId)
				.getLecturer();
		memberCount = RegisterationDAOImpl.getInstance().getAllCustId(courseId)
				.size();
		sinceDate = CourseDAOImpl.getInstance().getCourse(courseId)
				.getStartDate();

		HttpSession session = request.getSession();

		session.setAttribute("courseId", courseId);
		session.setAttribute("courseName", courseName);
		session.setAttribute("bNumber1", bNumber1);
		session.setAttribute("bNumber2", bNumber2);
		session.setAttribute("bNumber3", bNumber3);
		session.setAttribute("lecturer", lecturer);
		session.setAttribute("memberCount", memberCount);
		session.setAttribute("sinceDate", sinceDate);
		/*
		 * session.setAttribute("sms1", sms1); session.setAttribute("sms2",
		 * sms2); session.setAttribute("sms3", sms3);
		 * session.setAttribute("sms4", sms4); session.setAttribute("sms5",
		 * sms5);
		 */

		nextPage.setViewName("/course/index.jsp");

		// ///////////////////////////////////////

		return nextPage;
	}

	public ModelAndView insert(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView nextPage = new ModelAndView();

		String courseName = request.getParameter("courseName");
		String lecturerName = request.getParameter("lecturerName");
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		String startTime = request.getParameter("startTime");
		String endTime = request.getParameter("endTime");

		double absenceGrade = (100.0) / DateUtil.getNotHolidayDayCount(
				startDate, endDate);
		double earlyGrade = absenceGrade
				/ Integer.parseInt(request.getParameter("ealryGrade"));
		double lateGrade = absenceGrade
				/ Integer.parseInt(request.getParameter("lateGrade"));

		System.out.println("startDate :" + startDate);
		System.out.println("endDate :" + endDate);
		System.out.println("startTime : " + startTime);
		System.out.println("endTime : " + endTime);

		// ////////강좌 생성
		Course course = new Course();

		int courseId = CourseDAOImpl.getInstance().getMaxCourseId() + 1;
		// System.out.println(courseId);

		course.setCourseId(courseId);
		course.setCourseName(courseName);
		course.setLecturer(lecturerName);
		course.setStartDate(startDate);
		course.setEndDate(endDate);
		course.setStartTime(startTime);
		course.setEndTime(endTime);
		course.setAbsenceGrade(absenceGrade);
		course.setEarlyGrade(earlyGrade);
		course.setLateGrade(lateGrade);

		CourseDAOImpl.getInstance().insert(course);

		// ///////////////////////

		// //////커리큘럼 샘성

		// System.out.println("curriculumId : " + curriculumId);
		Curriculum curriculum = new Curriculum();
		curriculum.setCourseId(courseId);
		curriculum.setLecturerName(lecturerName);
		curriculum.setSubjectName(courseName);
		curriculum.setHourperWeek(DateUtil.getWeekHours(startTime, endTime));
		// System.out.println(curriculum);

		// CurriPlan생성
		// SimpleDateFormat temp=new SimpleDateFormat("yyyy/MM/dd");

		int weekCount = DateUtil.getWeekCount(startDate, endDate);

		curriculum.setWeeks(weekCount);

		CurriculumDAOImpl.getInstance().insert(curriculum);

		System.out.println("weekCount: " + weekCount);
		for (int i = 1; i <= weekCount; i++) {
			CurriPlan cp = new CurriPlan();
			cp.setCourseId(courseId);
			cp.setWeek(i);
			cp.setContent("");
			System.out.println("" + cp);
			CurriPlanDAOImpl.getInstance().insert(cp);
		}

		// ///////////게시판 생성

		Board board1 = new Board();// 공지사항
		int bNumber = BoardDAOImpl.getInstance().getMaxbNumber() + 1;
		int boardCourseId = courseId;
		String title = "공지사항";
		int accessPermission = 1;// 학생이상
		int writingPermission = 2;// 강사이상
		board1.setbNumber(bNumber);
		board1.setCourseId(boardCourseId);
		board1.setTitle(title);
		board1.setAccessPermission(accessPermission);
		board1.setWritingPermission(writingPermission);

		BoardDAOImpl.getInstance().insert(board1);

		Board board2 = new Board();// 자유게시판
		bNumber = BoardDAOImpl.getInstance().getMaxbNumber() + 1;
		boardCourseId = courseId;
		title = "자유게시판";
		accessPermission = 1;// 학생이상
		writingPermission = 1;// 강사이상
		board2.setbNumber(bNumber);
		board2.setCourseId(boardCourseId);
		board2.setTitle(title);
		board2.setAccessPermission(accessPermission);
		board2.setWritingPermission(writingPermission);
		BoardDAOImpl.getInstance().insert(board2);

		Board board3 = new Board();// 질문게시판

		bNumber = BoardDAOImpl.getInstance().getMaxbNumber() + 1;
		boardCourseId = courseId;
		title = "질문게시판";
		accessPermission = 1;// 학생이상
		writingPermission = 1;// 강사이상
		board3.setbNumber(bNumber);
		board3.setCourseId(boardCourseId);
		board3.setTitle(title);
		board3.setAccessPermission(accessPermission);
		board3.setWritingPermission(writingPermission);
		BoardDAOImpl.getInstance().insert(board3);

		// //////////출결등록관리 생성

		request.setAttribute("message", "클래스 등록 완료");

		nextPage.setViewName("index.jsp?contentMenu=admin/menuPage.jsp&content=admin/result.jsp");

		return nextPage;
	}

	public ModelAndView delete(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView nextPage;
		// System.out.println(request.getParameter("couresId"));
		int courseId = Integer.parseInt(request.getParameter("courseId"));
		CourseDAOImpl.getInstance().delete(courseId);

		RedirectView rv = new RedirectView("courseSearch.course");

		nextPage = new ModelAndView(rv);

		return nextPage;
	}

	public ModelAndView courseSearch(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView nextPage = new ModelAndView();

		ArrayList courseList = CourseDAOImpl.getInstance().getAllCourses();
		request.setAttribute("courseList", courseList);

		nextPage.setViewName("index.jsp?contentMenu=admin/menuPage.jsp&content=admin/courseSearch.jsp");

		return nextPage;
	}

	public ModelAndView courseUpdateView(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView nextPage = new ModelAndView();

		System.out.println("entered courseUpdateView");

		int courseId = Integer.parseInt(request.getParameter("courseId"));
		Course course = CourseDAOImpl.getInstance().getCourse(courseId);
		request.setAttribute("course", course);

		nextPage.setViewName("index.jsp?contentMenu=admin/menuPage.jsp&content=admin/courseUpdate.jsp");

		return nextPage;
	}

	public ModelAndView courseUpdate(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView nextPage = new ModelAndView();

		System.out.println("entered courseUpdate");

		int courseId = Integer.parseInt(request.getParameter("courseId"));
		Course course = CourseDAOImpl.getInstance().getCourse(courseId);

		String mStartDate = request.getParameter("startDate");// 변경된 시작날짜
		String mEndDate = request.getParameter("endDate");// 변경된 끝날짜
		String pStartDate = course.getStartDate();// 현재 시작날짜
		String pEndDate = course.getEndDate();// 현재 끝날짜

		String startTime = request.getParameter("startTime");
		String endTime = request.getParameter("endTime");
		String lecturer = request.getParameter("lecturerName");
		String courseName = request.getParameter("courseName");
		double absenceGrade = 100.0 / DateUtil.getNotHolidayDayCount(
				mStartDate, mEndDate);
		double earlyGrade = absenceGrade
				/ Integer.parseInt(request.getParameter("ealryGrade"));
		double lateGrade = absenceGrade
				/ Integer.parseInt(request.getParameter("lateGrade"));

		// System.out.println("점수 계산결과"+request.getParameter("ealryGrade")+" "+request.getParameter("lateGrade"));

		ArrayList<Registeration> userList = RegisterationDAOImpl.getInstance()
				.getAllConfirmCustId(courseId);
		/*
		 * SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd");
		 * Date dmStartDate = timeFormat.parse(mStartDate); Date dmEndDate =
		 * timeFormat.parse(mEndDate); Date dpStartDate =
		 * timeFormat.parse(pStartDate); Date dpEndDate =
		 * timeFormat.parse(pEndDate);
		 */
		for (int i = 0; i < userList.size(); i++) {

			if (CustomerDAOImpl.getInstance()
					.getCustomer(userList.get(i).getCustId()).getCustLevel() != 3)
				break;

			AttendInfoDAOImpl.getInstance().lowPeriodDelete(
					userList.get(i).getCustId(), courseId, mStartDate);
			AttendInfoDAOImpl.getInstance().highPeriodDelete(
					userList.get(i).getCustId(), courseId, mEndDate);

			String nextDate = mStartDate;
			int dayCount = DateUtil.getDayCount(
					DateUtil.getNextDay(mStartDate), mEndDate);

			for (int j = 0; j < dayCount; j++) {
				if (AttendInfoDAOImpl.getInstance().isExist(
						userList.get(i).getCustId(), courseId, nextDate)) {
					nextDate = DateUtil.getNextDay(nextDate);
					continue;
				}

				AttendInfo ai = new AttendInfo();
				ai.setCustId(userList.get(i).getCustId());
				ai.setCourseId(courseId);
				ai.setDay(nextDate);
				ai.setCheckInState(1);
				ai.setCheckOutState(1);
				ai.setCheckInTime("00:00");
				ai.setCheckOutTime("00:00");
				AttendInfoDAOImpl.getInstance().insert(ai);

				nextDate = DateUtil.getNextDay(nextDate);

			}
		}

		course.setCourseName(courseName);
		course.setLecturer(lecturer);
		course.setStartDate(mStartDate);
		course.setEndDate(mEndDate);
		course.setStartTime(startTime);
		course.setEndTime(endTime);
		course.setAbsenceGrade(absenceGrade);
		course.setEarlyGrade(earlyGrade);
		course.setLateGrade(lateGrade);

		System.out.println(course);

		CourseDAOImpl.getInstance().update(course);

		// //////커리큘럼 샘성

		// System.out.println("curriculumId : " + curriculumId);

		CurriculumDAOImpl.getInstance().delete(courseId);

		Curriculum curriculum = new Curriculum();
		curriculum.setCourseId(courseId);
		curriculum.setLecturerName(lecturer);
		curriculum.setSubjectName(courseName);
		curriculum.setHourperWeek(DateUtil.getWeekHours(startTime, endTime));
		// System.out.println(curriculum);

		// CurriPlan생성
		// SimpleDateFormat temp=new SimpleDateFormat("yyyy/MM/dd");

		int weekCount = DateUtil.getWeekCount(mStartDate, mEndDate);

		curriculum.setWeeks(weekCount);

		CurriculumDAOImpl.getInstance().insert(curriculum);

		CurriPlanDAOImpl.getInstance().allDelete(courseId);

		System.out.println("weekCount: " + weekCount);
		for (int i = 1; i <= weekCount; i++) {
			CurriPlan cp = new CurriPlan();
			cp.setCourseId(courseId);
			cp.setWeek(i);
			cp.setContent("");
			System.out.println("" + cp);
			CurriPlanDAOImpl.getInstance().insert(cp);
		}

		nextPage.setViewName("courseSearch.course");

		return nextPage;
	}

}
